<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="小程序," />





  <link rel="alternate" href="/atom.xml" title="Orton Blog" type="application/atom+xml" />






<meta name="description" content="不知不觉已经一个月没有写东西了，堕落的日子居然过的这么心（chou）安（bu）理（yao）得（lian），罪过啊。">
<meta name="keywords" content="小程序">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序的登录和数据解密全解析">
<meta property="og:url" content="http://ortonzhang.com/2018/11/27/mini-proaram-login-crypto/index.html">
<meta property="og:site_name" content="Orton Blog">
<meta property="og:description" content="不知不觉已经一个月没有写东西了，堕落的日子居然过的这么心（chou）安（bu）理（yao）得（lian），罪过啊。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/4/20/162e237d9f10d73d?w=835&h=794&f=jpeg&s=108228">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/4/20/162e23812d010151?w=752&h=281&f=jpeg&s=27598">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/4/20/162e2389d5e0fcb0?w=699&h=64&f=jpeg&s=26179">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/4/20/162e238b2bbf31d8?w=756&h=1162&f=png&s=110554">
<meta property="og:updated_time" content="2018-11-27T07:15:27.493Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="小程序的登录和数据解密全解析">
<meta name="twitter:description" content="不知不觉已经一个月没有写东西了，堕落的日子居然过的这么心（chou）安（bu）理（yao）得（lian），罪过啊。">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/4/20/162e237d9f10d73d?w=835&h=794&f=jpeg&s=108228">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://ortonzhang.com/2018/11/27/mini-proaram-login-crypto/"/>





  <title>小程序的登录和数据解密全解析 | Orton Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/Ortonzhang"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Orton Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Orton Blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://ortonzhang.com/2018/11/27/mini-proaram-login-crypto/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Orton Zhang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Orton Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">小程序的登录和数据解密全解析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-27T15:14:11+08:00">
                2018-11-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/小程序/" itemprop="url" rel="index">
                    <span itemprop="name">小程序</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 浏览
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,070
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>不知不觉已经一个月没有写东西了，堕落的日子居然过的这么心（chou）安（bu）理（yao）得（lian），罪过啊。</p>
<a id="more"></a>
<p>好了，回到正文来，聊咱们的小程序。</p>
<h2 id="致敬"><a href="#致敬" class="headerlink" title="致敬"></a>致敬</h2><p>登录大部分逻辑代码统统来自<a href="https://juejin.im/post/5ac9b72cf265da23906c486a" target="_blank" rel="external">手把手教会你小程序登录鉴权</a></p>
<h2 id="登录流程"><a href="#登录流程" class="headerlink" title="登录流程"></a>登录流程</h2><p><img src="https://user-gold-cdn.xitu.io/2018/4/20/162e237d9f10d73d?w=835&amp;h=794&amp;f=jpeg&amp;s=108228" alt=""></p>
<p>上图是官方给出的登录流程，我们来捋下逻辑。</p>
<p>1、用户使用<code>wx.login</code>获取临时<code>code</code>,有效期为5分钟</p>
<p>2、将临时<code>code</code>传到我们自己的后端服务，调用微信的API获取用户的<code>session_key</code>和<code>openid</code></p>
<p>3、后端自定义新的密钥并关联返回的<code>session_key</code>和<code>openid</code>，将新的密钥返给前端</p>
<p>4、前端发送请求的时候，带着密钥，后端进行解析后返回数据</p>
<h2 id="session-key和openid"><a href="#session-key和openid" class="headerlink" title="session_key和openid"></a>session_key和openid</h2><p>1、<code>session_key</code>会话密钥，用来确定会话的操作的有效性和用来加密解密用户数据，服务器自己存储即可，不应该将密钥返给前端和对话使用</p>
<p>2、<code>openid</code>用户唯一标识，同样只用于服务器,可以用来标识用户的唯一性</p>
<p>接下来，我们说下它们的获取,通过服务端调用微信API获取</p>
<p>API：<code>https://api.weixin.qq.com/sns/jscode2session</code></p>
<p>参数如下：</p>
<p><img src="https://user-gold-cdn.xitu.io/2018/4/20/162e23812d010151?w=752&amp;h=281&amp;f=jpeg&amp;s=27598" alt=""></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 小程序页面</span></div><div class="line">wx.login(&#123;</div><div class="line">	success:<span class="function">(<span class="params">ret</span>)=&gt;</span>&#123;</div><div class="line">		wx.request(&#123;</div><div class="line">			url: <span class="string">'http://test.com'</span>, <span class="comment">// 后端服务器</span></div><div class="line">			data:&#123;</div><div class="line">				code : ret.code</div><div class="line">			&#125;</div><div class="line">		&#125;)</div><div class="line">	&#125;</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>后端服务我们使用<code>request</code>模块来发送请求</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 后端服务</span></div><div class="line"><span class="keyword">let</span> options = &#123;</div><div class="line">  url: <span class="string">'https://api.weixin.qq.com/sns/jscode2session'</span>,</div><div class="line">  qs:&#123;</div><div class="line">      appid: appid,  </div><div class="line">      secret: secret,</div><div class="line">      js_code: code,</div><div class="line">      grant_type:<span class="string">'authorization_code'</span></div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 默认请求方式是get</span></div><div class="line">request(options, (err, response, body) =&gt; &#123;</div><div class="line">	<span class="keyword">if</span>(err) <span class="keyword">return</span> err</div><div class="line">	<span class="keyword">return</span> body  <span class="comment">// &#123;openid:'openid', session_key:'session_key'&#125; 不是真正的返回 看下面的代码</span></div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<h2 id="生成新的密钥-skey"><a href="#生成新的密钥-skey" class="headerlink" title="生成新的密钥 skey"></a>生成新的密钥 skey</h2><p>上面我们获取了session_key和openid，下文两个字断称keyID，接下来我们生成一个新的密钥返回前端并将新密钥关联keyID。</p>
<p>我们使用crypto模块的sha1算法生成密钥</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">'crypto'</span>)</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">getShaKey</span>(<span class="params">data</span>)</span>&#123;</div><div class="line">	<span class="keyword">return</span> crypto.createHash(<span class="string">'sha1'</span>).update(data, <span class="string">'utf8'</span>).digest(<span class="string">'hex'</span>)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上面的代码返回我们就改成这个新的skey，前端将这个密钥存在storage里面，请求的时候带上这个skey，就完成了自定义登录态。</p>
<h2 id="wx-checkSession"><a href="#wx-checkSession" class="headerlink" title="wx.checkSession"></a>wx.checkSession</h2><p>用来校验当前用户的session_key是否有效，微信不会把session_key的有效期告知开发者，用户越频繁使用小程序，session_key有效期越长。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">wx.checkSession(&#123;</div><div class="line">	success:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;  <span class="comment">// 当前session_key有效</span></div><div class="line">		... <span class="comment">// 可以写我们的业务代码</span></div><div class="line">	&#125;,</div><div class="line">	fail:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;   <span class="comment">// 当前session_key已过期</span></div><div class="line">		wx.login()  <span class="comment">// 重新登录，获取新的session_key</span></div><div class="line">	&#125;</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>当session_key过期的时候，我们调用登录API，更新session_key生成新的skey，并关联二者关系。</p>
<h2 id="工具函数的封装"><a href="#工具函数的封装" class="headerlink" title="工具函数的封装"></a>工具函数的封装</h2><p>前面我们将流程大概串了下，接下来我们把上面的流程写成写成公用的函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">// 验证session_key状态</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">checkSession</span>(<span class="params"></span>)</span>&#123;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</div><div class="line">		wx.checkSession(&#123;</div><div class="line">			success:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">				resolve(<span class="literal">true</span>)</div><div class="line">			&#125;,</div><div class="line">			fail:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">				reject(<span class="literal">false</span>)</div><div class="line">			&#125;</div><div class="line">		&#125;)</div><div class="line">	&#125;)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 登录</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">login</span>(<span class="params"></span>)</span>&#123;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</div><div class="line">		wx.login(&#123;</div><div class="line">			success: <span class="function">(<span class="params">ret</span>) =&gt;</span> &#123;</div><div class="line">				wx.request(&#123;</div><div class="line">					url:<span class="string">'本地服务地址'</span>,</div><div class="line">					method: <span class="string">'POST'</span>,</div><div class="line">					data:&#123;</div><div class="line">						code: ret.code</div><div class="line">					&#125;,</div><div class="line">					success: <span class="function">(<span class="params">response</span>) =&gt;</span>&#123;</div><div class="line">						wx.setStorageSync(<span class="string">'skey'</span>, response.data.key)  <span class="comment">// 将skey存在storage里面</span></div><div class="line">						resolve(response.data.key)</div><div class="line">					&#125;</div><div class="line">					</div><div class="line">				&#125;)</div><div class="line">			&#125;</div><div class="line">		&#125;)</div><div class="line">		</div><div class="line">	&#125;)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 请求</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url, data, method=<span class="string">"GET"</span>, config=&#123;&#125;</span>)</span>&#123;</div><div class="line">	<span class="keyword">let</span> skey = wx.getStorageSync(<span class="string">'skey'</span>) <span class="comment">// 获取skey</span></div><div class="line">	<span class="keyword">if</span>(!skey)&#123;  <span class="comment">// 没有skey，首次登录</span></div><div class="line">		<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</div><div class="line">			login()</div><div class="line">			reject(<span class="string">'请登录'</span>)</div><div class="line">		&#125;)</div><div class="line">	&#125; <span class="keyword">else</span> &#123;</div><div class="line">		<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</div><div class="line">      checkSession().then( <span class="function"><span class="params">_</span>=&gt;</span> &#123;</div><div class="line">        <span class="keyword">if</span> (_)&#123; <span class="comment">// session_key有效</span></div><div class="line">          wx.request(&#123;</div><div class="line">            url,</div><div class="line">            method: method.toLocaleUpperCase(),</div><div class="line">            data,</div><div class="line">            header: <span class="built_in">Object</span>.assign(&#123;&#125;, &#123; skey &#125;, config),</div><div class="line">            success: <span class="function">(<span class="params">ret</span>) =&gt;</span> &#123;</div><div class="line">              resolve(ret.data)</div><div class="line">            &#125;</div><div class="line">          &#125;)</div><div class="line">        &#125; <span class="keyword">else</span> &#123; <span class="comment">// session_key失效</span></div><div class="line">          login()</div><div class="line">          reject(<span class="string">'session_key失效'</span>)</div><div class="line">        &#125;</div><div class="line">      &#125;)</div><div class="line">    &#125;)</div><div class="line"></div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="后端代码"><a href="#后端代码" class="headerlink" title="后端代码"></a>后端代码</h2><p>后端使用<a href="https://koa.bootcss.com/#" target="_blank" rel="external">koa框架</a>，代码见文末<code>github</code>地址</p>
<h2 id="解密"><a href="#解密" class="headerlink" title="解密"></a>解密</h2><p>官方提供了多种编程语言的示例代码<a href="https://developers.weixin.qq.com/miniprogram/dev/demo/aes-sample.zip" target="_blank" rel="external">点击下载</a></p>
<p>这里我们使用微信运动API为例</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> app = getApp()  <span class="comment">// 我们将工具函数都放在了app的示例上面</span></div><div class="line">Page(&#123;</div><div class="line">	onLoad:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">		app.Util.login().then(<span class="function"><span class="params">_</span> =&gt;</span> &#123;  <span class="comment">// 先登录然后获取数据</span></div><div class="line">      <span class="keyword">this</span>.getrunData()</div><div class="line">    &#125;)</div><div class="line">	&#125;,</div><div class="line">	getrunData()&#123;</div><div class="line">    wx.getWeRunData(&#123;</div><div class="line">      success: <span class="function">(<span class="params">ret</span>) =&gt;</span> &#123;</div><div class="line">        app.Util.ajax(<span class="string">'本地服务地址'</span>, &#123; <span class="attr">iv</span>: ret.iv, <span class="attr">data</span>: ret.encryptedData&#125;, <span class="string">'post'</span>).then(<span class="function"><span class="params">_</span>=&gt;</span>&#123;</div><div class="line">          <span class="built_in">console</span>.log(_)</div><div class="line">        &#125;, (err)=&gt;&#123;</div><div class="line">          <span class="built_in">console</span>.log(err)</div><div class="line">        &#125;)</div><div class="line">      &#125;</div><div class="line">    &#125;)</div><div class="line">  &#125;,</div><div class="line"></div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>返回结果如下</p>
<p><img src="https://user-gold-cdn.xitu.io/2018/4/20/162e2389d5e0fcb0?w=699&amp;h=64&amp;f=jpeg&amp;s=26179" alt=""></p>
<p>以上，我们完成了小程序简单的登录鉴权和数据解密</p>
<h2 id="效果图镇楼"><a href="#效果图镇楼" class="headerlink" title="效果图镇楼"></a>效果图镇楼</h2><p><img src="https://user-gold-cdn.xitu.io/2018/4/20/162e238b2bbf31d8?w=756&amp;h=1162&amp;f=png&amp;s=110554" alt=""></p>
<h2 id="结尾"><a href="#结尾" class="headerlink" title="结尾"></a>结尾</h2><p>登录鉴权我们只是将用户状态放在了内存里，实际项目中肯定要放在数据库中，可以拜读下<a href="https://juejin.im/post/5ac9b72cf265da23906c486a" target="_blank" rel="external">大神文章</a>，里面说到了数据库的操作。</p>
<p>再次致敬</p>
<p>本文完整代码请戳<a href="https://github.com/Ortonzhang/simple-code/tree/master/javascript/user-crypto" target="_blank" rel="external">github</a></p>

      
    </div>
    
    
    
    
      <div>
        
<div class="my_post_copyright">
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.7.1/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/sweetalert/1.1.2/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/sweetalert/1.1.2/sweetalert.min.css">
  <p><span>本文作者:</span><a href="/" title="访问 Orton Zhang 的个人博客">Orton Zhang</a></p>
  <p><span>本文链接:</span><a href="/2018/11/27/mini-proaram-login-crypto/" title="小程序的登录和数据解密全解析">http://ortonzhang.com/2018/11/27/mini-proaram-login-crypto/</a>
  </p>
  <p><span>版权声明:</span>本博客所有文章除特别声明外，均采用<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/cn/" target="_blank" title="CC BY-NC-SA 3.0 CN">CC BY-NC-SA 3.0 CN</a> 许可协议。转载请注明出处！</p>  
</div>

      </div>
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/小程序/" rel="tag"><i class="fa fa-tag"></i> 小程序</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/27/css-shapes/" rel="next" title="shapes 创建炫酷的内容流">
                <i class="fa fa-chevron-left"></i> shapes 创建炫酷的内容流
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="Orton Zhang" />
            
              <p class="site-author-name" itemprop="name">Orton Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/Ortonzhang" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://weibo.com/5189572269/profile?rightmod=1&wvr=6&mod=personinfo" target="_blank" title="weibo">
                    
                      <i class="fa fa-fw fa-globe"></i>weibo</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#致敬"><span class="nav-number">1.</span> <span class="nav-text">致敬</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#登录流程"><span class="nav-number">2.</span> <span class="nav-text">登录流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#session-key和openid"><span class="nav-number">3.</span> <span class="nav-text">session_key和openid</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生成新的密钥-skey"><span class="nav-number">4.</span> <span class="nav-text">生成新的密钥 skey</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#wx-checkSession"><span class="nav-number">5.</span> <span class="nav-text">wx.checkSession</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#工具函数的封装"><span class="nav-number">6.</span> <span class="nav-text">工具函数的封装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后端代码"><span class="nav-number">7.</span> <span class="nav-text">后端代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#解密"><span class="nav-number">8.</span> <span class="nav-text">解密</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#效果图镇楼"><span class="nav-number">9.</span> <span class="nav-text">效果图镇楼</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结尾"><span class="nav-number">10.</span> <span class="nav-text">结尾</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Orton Zhang</span>

  
</div>



<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共13.0k字</span>
</div>

<span id="busuanzi_container_site_uv">
  访问次数:<span id="busuanzi_value_site_uv"></span>
</span>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  





  

  

  
  

  

  

  

</body>
</html>
